import hashlib
import logging
import os
import re
import urllib.request

logger = logging.getLogger()


class ufile:
    def __init__(self, dir, exts=['md'], target_file_marker="_local"):
        """

        :param dir: the directory you want to scan
        :param exts: the ext of file, not include the dot. the md represents the .md.
        :param target_file_marker:
        ---

        target_file_marker:
        ---
        """

        self._dir = dir
        self._exts = exts
        self._target_file_marker = target_file_marker

    def get_markdown_files(self):
        self._files = []
        self._scan_dir(self._dir)
        return self._files

    def _scan_dir(self, crnt_dir):
        files = os.listdir(crnt_dir)
        for f in files:
            f_abs = os.path.join(crnt_dir, f)
            f_ext = f.split(".")[-1]
            f_name = f.split(".")[0]

            if f_ext in self._exts and os.path.isfile(f_abs):
                self._files.append(f_abs)
            elif os.path.isdir(f_abs):
                self._scan_dir(f_abs)

    def get_file_marker(self, f_name: str):
        t_names = os.path.basename(f_name).split(".")
        f_name = ".".join(t_names[:-1])
        f_ext = t_names[-1]
        t_target_names = [f_name, self._target_file_marker, ".", f_ext]

        return "".join(t_target_names)


class umarkdown:
    def __init__(self, file, image_base_dir):
        """

        :param file:  the markdown file
        :param image_base_dir:  the  directory to save image
        """

        self._file = file
        self._base_image_dir = image_base_dir
        logger.info("file %s,image_dir %s" % (self._file,self._base_image_dir))

    def get_local_markdown(self):
        with open(self._file, 'r') as f:
            content = f.read()

        #         查找所有的链接
        links = re.findall('!\[(.*)\]\((.*)\)', content)
        for i in range(len(links)):
            img_quote = links[i][0]
            img_url = links[i][1]
            replace_img = uimage().download_image(img_url, base_dir=self._base_image_dir)
            if replace_img:
                content = content.replace(img_url, replace_img.split("./")[-1])
        return content


class uimage:

    def __init__(self, img_ext="png"):
        self._img_ext = img_ext

    def get_image_ext(self):
        return "." + self._img_ext

    def download_image(self, img_url:str, base_dir) -> str:
        if not (img_url.startswith("http") or img_url.startswith("https")):
            logger.info("not download image %s"%img_url)
            return

        if not os.path.exists(base_dir):
            os.makedirs(base_dir)

        pic_name = os.path.join(base_dir, self.get_url_hash(img_url) + "." + self._img_ext)
        if os.path.exists(pic_name):
            return pic_name

        try:

            urllib.request.urlretrieve(img_url, pic_name)
            if os.path.isfile(pic_name):
                return pic_name
            else:
                logger.error("File %s is not existed" % pic_name)
                return None
        except Exception as e:
            logger.error(e)

    @staticmethod
    def get_url_hash(url: str) -> str:
        m = hashlib.md5()
        m.update(url.encode("UTF-8"))
        return str(m.hexdigest())
